package com.rookie.shiro.module.config;

import com.rookie.shiro.module.entity.PermissionDocEntity;
import com.rookie.shiro.module.util.PermissionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component
public class BeanLoadedApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private ShiroFilterFactoryBean shiroFilterFactoryBean;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        updatePermission(shiroFilterFactoryBean);
    }

    public Map<String, String> loadFilterChainDefinitions() {
        List<PermissionDocEntity> list = PermissionUtils.listPermissions(applicationContext, "com.XXX.controller");;
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
//        配置过滤器名决定过滤器执行的顺序

        filterChainDefinitionMap.put("/2", "anon");
        filterChainDefinitionMap.put("/111", "jwt,perms[666]");
        for (PermissionDocEntity tmp : list) {
            if (StringUtils.isBlank(tmp.getUrl())){
                continue;
            }
            if (tmp.isAnonymous()) {
                filterChainDefinitionMap.put(tmp.getUrl(), "anon");
            } else {
                filterChainDefinitionMap.put(tmp.getUrl(), "jwt,perms[" + tmp.getPermission() + "]");
            }
        }
        filterChainDefinitionMap.put("/**", "jwt");

        return filterChainDefinitionMap;
    }

    public void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean) {
        synchronized (this) {
            AbstractShiroFilter shiroFilter;
            try {
                shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
            } catch (Exception e) {
                throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!");
            }

            if (shiroFilter == null){
                return;
            }
            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();

            // 清空老的权限控制
            manager.getFilterChains().clear();

            shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
            shiroFilterFactoryBean.setFilterChainDefinitionMap(loadFilterChainDefinitions());
            // 重新构建生成
            Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim()
                        .replace(" ", "");
                manager.createChain(url, chainDefinition);
            }
        }
    }
}
